<template>
  <view class="category-linkage">
    <!-- 左侧分类 -->
    <view class="category-linkage__left">
      <scroll-view
        class="category-linkage__left__scroll"
        scroll-y
        :scroll-top="leftScrollTop"
      >
        <view
          v-for="(item, index) in leftCategoryList"
          :key="index"
          :class="['category-linkage__left__item', activeIndex === index ? 'category-linkage__left__item--active' : '']"
        >
        <view v-if="activeIndex === index" class="kuai"></view>
          <text
            :class="[
              'category-linkage__left__text',
              activeIndex === index
                ? 'category-linkage__left__text--active'
                : '',
            ]"
            @tap="handleLeftItemClick(index)"
            >{{ item[leftFieldName] }}</text
          >
        </view>
      </scroll-view>
    </view>

    <!-- 右侧内容 -->
    <view class="category-linkage__right">
      <scroll-view
        ref="rightScrollView"
        class="category-linkage__right__scroll"
        scroll-y
        :scroll-top="rightScrollTop"
        @scroll="handleRightScroll"
        scroll-with-animation
      >
        <view
          v-for="(item, index) in rightCategoryList"
          :key="index"
          :id="'rightItem' + index"
          class="category-linkage__right__item"
        >
          <u-sticky
            :offset-top="stickyTop"
            @fixed="onStickyChange(index, $event)"
          >
            <view class="category-linkage__right__title sticky-item">{{
              item[rightFieldName]
            }}</view>
          </u-sticky>
          <slot name="rightitem" :rightItem="item[rightChildListName]">
            <view
              v-if="
                item[rightChildListName] && item[rightChildListName].length > 0
              "
              class="category-linkage__right__children"
            >
              <view
                v-for="(child, childIndex) in item[rightChildListName]"
                :key="childIndex"
                class="category-linkage__right__child-item"
              >
                {{ child[rightChildName] }}
              </view>
            </view>
          </slot>
        </view>
      <view class="bottom">数据已全部加载~</view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
export default {
  name: "CategoryLinkage",
  props: {
    // 分类数据
    categoryData: {
      type: Array,
      default: () => [],
    },
    // 左侧分类显示字段
    leftFieldName: {
      type: String,
      default: "name",
    },
    // 右侧分类显示字段
    rightFieldName: {
      type: String,
      default: "name",
    },
    // 右侧子级显示字段
    rightChildName: {
      type: String,
      default: "name",
    },
    // 右侧子级列表字段
    rightChildListName: {
      type: String,
      default: "children",
    },
    // 滚动动画时间（ms）
    scrollDuration: {
      type: Number,
      default: 500,
    },
    // 滚动阈值，用于判断哪个分类在可视区域
    scrollThreshold: {
      type: Number,
      default: 100,
    },
    // 吸顶距离顶部的距离
    stickyTop: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      activeIndex: 0, // 当前激活的左侧分类索引
      leftScrollTop: 0, // 左侧滚动条位置
      rightScrollTop: 0, // 右侧滚动条位置
      itemHeights: [], // 存储每个右侧分类的高度
      itemOffsets: [], // 存储每个右侧分类的位置
      totalHeight: 0, // 右侧总高度
      isScrolling: false, // 是否正在滚动
      stickyItemHeight: 40, // 吸顶项的高度
      currentStickyIndex: -1, // 当前吸顶的项索引
    };
  },
  computed: {
    // 处理后的左侧分类列表
    leftCategoryList() {
      return this.categoryData.map((item) => ({
        [this.leftFieldName]: item[this.leftFieldName],
      }));
    },
    // 处理后的右侧分类列表
    rightCategoryList() {
      console.log(this.categoryData, 'categoryData');
      
      return this.categoryData;
    },
  },
  mounted() {
    this.calculateItemPositions();
  },
  methods: {
    // 计算每个分类项的位置
    calculateItemPositions() {
      const query = uni.createSelectorQuery().in(this);

      // 获取所有右侧分类项的位置和高度
      query
        .selectAll(".category-linkage__right__item")
        .boundingClientRect((res) => {
          if (res) {
            this.itemHeights = res.map((item) => item.height);
            this.totalHeight = this.itemHeights.reduce(
              (sum, height) => sum + height,
              0
            );

            // 计算每个项的偏移量
            let offset = 0;
            this.itemOffsets = res.map((item) => {
              const currentOffset = offset;
              offset += item.height;
              return currentOffset;
            });
            console.log(this.itemOffsets);

            // 计算滚动位置
            this.handleRightScrollPosition();
          }
        })
        .exec();
    },

    // 处理左侧分类点击事件
    handleLeftItemClick(index) {
      if (this.activeIndex !== index) {
        this.activeIndex = index;

        // 滚动到对应右侧内容
        const targetOffset = this.itemOffsets[index] || 0;
        this.scrollToPosition(targetOffset);
      }
    },

    // 处理右侧滚动事件
    handleRightScroll(e) {
      if (this.isScrolling) {
        this.isScrolling = false;
        return;
      }

      const scrollTop = e.detail.scrollTop;
      let currentIndex = 0;

      // 查找当前滚动位置对应的分类
      for (let i = 0; i < this.itemOffsets.length; i++) {
        if (scrollTop >= this.itemOffsets[i] - this.scrollThreshold) {
          currentIndex = i;
        }
      }

      // 更新左侧选中项
      if (currentIndex !== this.activeIndex) {
        this.activeIndex = currentIndex;

        // 滚动左侧菜单
        const itemHeight = 40; // 假设每个左侧菜单项高度为40px
        this.leftScrollTop = currentIndex * itemHeight - itemHeight * 2;
      }

      // 更新吸顶状态
      this.updateStickyStatus(scrollTop);
    },

    // 更新吸顶状态
    updateStickyStatus(scrollTop) {
      // 查找当前处于吸顶状态的项
      let stickyIndex = -1;
      for (let i = 0; i < this.itemOffsets.length; i++) {
        if (
          scrollTop >= this.itemOffsets[i] &&
          (i === this.itemOffsets.length - 1 ||
            scrollTop < this.itemOffsets[i + 1] - this.stickyItemHeight)
        ) {
          stickyIndex = i;
          break;
        }
      }

      if (stickyIndex !== this.currentStickyIndex) {
        this.currentStickyIndex = stickyIndex;
        // 这里可以添加额外的吸顶状态变化处理逻辑
      }
    },

    // 处理吸顶状态变化
    onStickyChange(index, isFixed) {
      if (isFixed) {
        this.currentStickyIndex = index;
      } else if (this.currentStickyIndex === index) {
        this.currentStickyIndex = -1;
      }
    },

    // 滚动到指定位置
    scrollToPosition(offset) {
      this.isScrolling = true;
      this.rightScrollTop = offset;

      // 在下一个tick后重置isScrolling，确保动画完成
      this.$nextTick(() => {
        setTimeout(() => {
          this.isScrolling = false;
        }, this.scrollDuration);
      });
    },

    // 处理右侧滚动位置
    handleRightScrollPosition() {
      // 这里可以添加额外的初始化逻辑
    },
  },
};
</script>

<style lang="scss" scoped>
.category-linkage {
  display: flex;
  height: 100%;

  &__left {
    width: 25%;
    background-color: #f6f6f6;

    &__scroll {
      height: 100%;
    }

    &__item {
      
      padding:30rpx 0rpx;
      border-bottom: 1px solid #eee;
      position: relative;
      &--active {
        border-bottom: none;
        background-color: #fff;
      }
      // .kuai{
      //   position: absolute;
      //   width: 40rpx;
      //   height: 40rpx;
      //   border-radius: 50%;
      //   bottom: 0rpx;
      //   right: 0rpx;
      //   background-color: #fff;
      // }
    }

    &__text {
      display: block;
      font-size: 28rpx;
      color: #C8C9CC;
      text-align: center;
      width: 100%;

      &--active {
        color: #000000;
        background-color: #fff;
        font-weight: bold;
        border-left: 8rpx solid #a22d27;

      }
    }
  }

  &__right {
    flex: 1;
    padding: 15px;

    &__scroll {
      height: 100%;
    }

    &__title {
      font-size: 24rpx;
      color: #C8C9CC;
      margin-bottom: 10px;
      background-color: #ffffff;
      z-index: 999;
    }

    &__children {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
      gap: 10px;
    }

    &__child-item {
      padding: 8px;
      background-color: #f0f0f0;
      text-align: center;
      border-radius: 4px;
    }
  }
  .sticky-item {
    padding: 34rpx 0;
  }
}
.bottom{
  padding-bottom: 60vh;
  color: #c8c9cc;
  font-size: 24rpx;
  text-align: center;
}
</style>
